<?php
// JWT认证类
// core/Auth.php
class Auth {
    protected $secret;
    
    public function __construct($secret) {
        $this->secret = $secret;
    }
    
    public function attempt($credentials) {
        // 验证用户凭据的逻辑
        // 如果验证成功，生成并返回JWT token
        $payload = [
            'sub' => $credentials['id'],
            'email' => $credentials['email'],
            'iat' => time(),
            'exp' => time() + (60 * 60 * 24) // 24小时过期
        ];
        
        return $this->generateToken($payload);
    }
    
    public function generateToken($payload) {
        $header = json_encode(['typ' => 'JWT', 'alg' => 'HS256']);
        $payload = json_encode($payload);
        
        $base64UrlHeader = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($header));
        $base64UrlPayload = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($payload));
        
        $signature = hash_hmac('sha256', $base64UrlHeader . "." . $base64UrlPayload, $this->secret, true);
        $base64UrlSignature = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($signature));
        
        return $base64UrlHeader . "." . $base64UrlPayload . "." . $base64UrlSignature;
    }
    
    public function validateToken($token) {
        // 验证JWT token的逻辑
        list($header, $payload, $signature) = explode('.', $token);
        
        $validSignature = hash_hmac('sha256', $header . "." . $payload, $this->secret, true);
        $validSignatureBase64 = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($validSignature));
        
        if ($signature !== $validSignatureBase64) {
            return false;
        }
        
        $decodedPayload = json_decode(base64_decode(str_replace(['-', '_'], ['+', '/'], $payload)), true);
        
        if (isset($decodedPayload['exp']) && $decodedPayload['exp'] < time()) {
            return false;
        }
        
        return $decodedPayload;
    }
}